import { nextTick } from 'vue';
let lock = true;
let el = null;
const MousedownEvent = document.createEvent('HTMLEvents');
MousedownEvent.initEvent('mousedown', true, false);
const MouseupEvent = document.createEvent('HTMLEvents');
MouseupEvent.initEvent('mouseup', true, false);
const fakeClickOutSide = () => {
  document.dispatchEvent(MousedownEvent);
  document.dispatchEvent(MouseupEvent);
  lock = true;
};
const mousedownHandle = e => {
  const { classList } = e.target;
  if (
    classList.contains('el-select-dropdown') ||
    classList.contains('el-select__caret') ||
    classList.contains('el-input__inner')
  ) {
    lock = false;
    return;
  }
  if (lock) {
    return;
  }
  fakeClickOutSide();
};
const mousewheelHandle = e => {
  if (
    lock ||
    e.target.classList.contains('el-select-dropdown__item') ||
    e.target.parentNode.classList.contains('el-select-dropdown__item')
  ) {
    return;
  }
  fakeClickOutSide();
};
const eventListener = type => {
  el && el[`${type}EventListener`]('mousedown', mousedownHandle);
  window && window[`${type}EventListener`]('mousewheel', mousewheelHandle);
  window && window[`${type}EventListener`]('DOMMouseScroll', mousewheelHandle);
};
export default {
  mounted() {
    el = this.$root.$el;
    el.addFakeClickOutSideEventCount = el.addFakeClickOutSideEventCount || 0;

    if (!el.addFakeClickOutSideEventCount) {
      nextTick(() => {
        eventListener('add');
      });
    }
    el.addFakeClickOutSideEventCount += 1;
  },
  unmounted() {
    eventListener('remove');
    el.addFakeClickOutSideEventCount = null;
  },
};
